//
//  UITableView+Extension.swift
//  Lease_IOS
//
//  Created by Mr.wang on 2018/12/20.
//  Copyright © 2018 Mr.wang. All rights reserved.
//

import UIKit
import RxSwift
import RxDataSources
import RxCocoa

extension UITableView {
    
    func autoSelect(at indexPath: IndexPath) {
        self.rx.methodInvoked(#selector(reloadData))
            .bind{ [weak self] _ in
                guard let self = self,
                    indexPath.section < self.numberOfSections,
                    indexPath.row < self.numberOfRows(inSection: indexPath.section),
                    self.indexPathsForSelectedRows == nil else { return }
                self.selectRow(at: indexPath, animated: true, scrollPosition: .top)
            }.disposed(by: rx.disposeBag)
    }
    
    func setHeaderHeight(_ height : CGFloat) {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: height))
        view.backgroundColor = .clear
        self.tableHeaderView = view
    }
    
    func register<Cell: UITableViewCell>(_ cellType: Cell.Type) {
        register(cellType, forCellReuseIdentifier: Cell.reuseIdentifier)
    }
    
    func dequeueReusableCell<Cell: UITableViewCell>(_ cellType: Cell.Type) -> Cell {
        guard let cell = dequeueReusableCell(withIdentifier: Cell.reuseIdentifier) as? Cell else {
            fatalError("tableview没有注册cell")
        }
        return cell
    }
    
    func registerForHeaderFooterView<View: UITableViewHeaderFooterView>(_ viewType: View.Type) {
        register(viewType, forHeaderFooterViewReuseIdentifier: View.reuseIdentifier)
    }
    
    func dequeueHeaderFooterView<View: UITableViewHeaderFooterView>(_ viewType: View.Type) -> View? {
        return dequeueReusableHeaderFooterView(withIdentifier: View.reuseIdentifier) as? View
    }
}

extension UITableViewCell {
    
    func superTableView() -> UITableView? {
        for view in sequence(first: self.superview, next: { $0?.superview }) {
            if let tableView = view as? UITableView {
                return tableView
            }
        }
        return nil
    }
}

extension Reactive where Base: UITableView {
    
    public func items<S: Sequence, Cell: UITableViewCell, O : ObservableType>
        (cellType: Cell.Type = Cell.self)
        -> (_ source: O)
        -> (_ configureCell: @escaping (Int, S.Iterator.Element, Cell) -> Void)
        -> Disposable
        where O.Element == S {
            return self.items(cellIdentifier: cellType.reuseIdentifier, cellType: cellType)
    }
    
}
